<?php
    /*

     Version: MPL 1.1

     Software distributed under the License is distributed on an "AS IS"
     basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
     License for the specific language governing rights and limitations
     under the License.

     The Original Code is KASSIOP Framework.

     The Initial Developer of the Original Code is SURIAN Nicolas (aka NairuS) <me@nairus.fr>.
     Portions created by the Initial Developer are Copyright (C) 2010
     The Initial Developer. All Rights Reserved.

     Contributor(s):

     Alternatively, the contents of this file may be used under the terms
     of the MPL license Version 1.1 (the  "MPL" License"), in which case the
     provisions of Version: MPL 1.1 License are applicable instead of those
     above.  If you wish to allow use of your version of this file only
     under the terms of the MPL License and not to allow others to use
     your version of this file under the MPL, indicate your decision by
     deleting  the provisions above and replace  them with the notice and
     other provisions required by the MPL License.  If you do not delete
     the provisions above, a recipient may use your version of this file
     under either the MPL License.

     The contents of this file are subject to the Mozilla Public License
     Version 1.1 (the "License"); you may not use this file except in
     compliance with the License. You may obtain a copy of the License at
     http://www.mozilla.org/MPL/

    */

    /**
     * FileValidator validates an uploaded file.
     *
     * @package    kassiop.system
     * @subpackage validators
     *
     * @author NairuS
     * @version 1.2 $Rev: 90 $ $Date: 2011-01-16 09:23:26 +0000 (Sun, 16 Jan 2011) $ $Author: nicolas.surian $
     */
    class FileValidator extends BaseValidator
    {
        /**
         * Defines the cant_write option key.
         *
         * @var string
         */
        public static $cantWriteKey          = 'cant_write';

        /**
         * Defines the extension option key.
         *
         * @var string
         */
        public static $extensionKey          = 'extension';

        /**
         * Defines the max_size option key.
         *
         * @var string
         */
        public static $maxSizeKey            = 'max_size';


        /**
         * Defines the mime_categories option key.
         *
         * @var string
         */
        public static $mimeCategoriesKey     = 'mime_categories';

        /**
         * Defines the mime_type_guessers option key.
         *
         * @var string
         */
        public static $mimeTypeGuessersKey   = 'mime_type_guessers';

        /**
         * Defines the mime_types option key.
         *
         * @var string
         */
        public static $mimeTypeKey           = 'mime_types';
        /**
         * Defines the no_tmp_dir option key.
         *
         * @var string
         */
        public static $noTmpDirKey           = 'no_tmp_dir';

        /**
         * Defines the partial option key.
         *
         * @var string
         */
        public static $partialKey            = 'partial';

        /**
         * Defines the path option key.
         *
         * @var string
         */
        public static $pathKey               = 'path';

        /**
         * Defines the validated_file_class option key.
         *
         * @var string
         */
        public static $validatedFileClassKey = 'validated_file_class';

        /**
         * Configures the current validator.
         *
         * Available options:
         *
         *  * max_size:             The maximum file size in bytes (cannot exceed upload_max_filesize in php.ini)
         *  * mime_types:           Allowed mime types array or category (available categories: web_images)
         *  * mime_type_guessers:   An array of mime type guesser PHP callables (must return the mime type or null)
         *  * mime_categories:      An array of mime type categories (web_images is defined by default)
         *  * path:                 The path where to save the file - as used by the ValidatedFile class (optional)
         *  * validated_file_class: Name of the class that manages the cleaned uploaded file (optional)
         *
         * There are 3 built-in mime type guessers:
         *
         *  * guessFromFileinfo:        Uses the finfo_open() function (from the Fileinfo PECL extension)
         *  * guessFromMimeContentType: Uses the mime_content_type() function (deprecated)
         *  * guessFromFileBinary:      Uses the file binary (only works on *nix system)
         *
         * Available error codes:
         *
         *  * max_size
         *  * mime_types
         *  * partial
         *  * no_tmp_dir
         *  * cant_write
         *  * extension
         *
         * @see BaseValidator
         */
        protected function configure()
        {
            if( !ini_get( 'file_uploads' ) )
            {
              throw new LogicException( sprintf( 'Unable to use a file validator as "file_uploads" is disabled in your php.ini file (%s)', get_cfg_var( 'cfg_file_path' ) ) );
            }

            // add the required options.
            $this->addOption( self::$maxSizeKey );
            $this->addOption( self::$mimeTypeKey );
            $this->addOption( self::$mimeTypeGuessersKey, array(
                array( $this, 'guessFromFileinfo' ),
                array( $this, 'guessFromMimeContentType' ),
                array( $this, 'guessFromFileBinary' ),
                )
            );
            $this->addOption( self::$mimeCategoriesKey, array(
                'web_images' => array(
                    'image/jpeg',
                    'image/pjpeg',
                    'image/png',
                    'image/x-png',
                    'image/gif',
                    )
                )
            );
            $this->addOption( self::$pathKey, null );
            $this->addOption( self::$validatedFileClassKey, 'ValidatedFile' );

            // set the messages.
            $this->addMessage( self::$cantWriteKey, 'Failed to write file to disk.' );
            $this->addMessage( self::$extensionKey, 'File upload stopped by extension.' );
            $this->addMessage( self::$maxSizeKey  , 'File is too large (maximum is %' . self::$maxSizeKey . '% bytes).' );
            $this->addMessage( self::$mimeTypeKey , 'Invalid mime type (%' . self::$mimeTypeKey . '%).' );
            $this->addMessage( self::$noTmpDirKey , 'Missing a temporary folder.' );
            $this->addMessage( self::$partialKey  , 'The uploaded file was only partially uploaded.' );
        }

        /**
         * This validator always returns a ValidatedFile object.
         *
         * The input value must be an array with the following keys:
         *
         *  * tmp_name: The absolute temporary path to the file
         *  * name:     The original file name (optional)
         *  * type:     The file content type (optional)
         *  * error:    The error code (optional)
         *  * size:     The file size in bytes (optional)
         *
         * @see BaseValidator
         */
        protected function doClean($value)
        {

        if( !is_array($value) || !isset( $value['tmp_name'] ) )
        {
            throw new ErrorBaseValidator( $this, self::$invalidKey, array( 'value' => (string) $value ) );
        }

        if( !isset( $value['name'] ) )
        {
            $value['name'] = '';
        }

        if( !isset($value['error'] ) )
        {
            $value['error'] = UPLOAD_ERR_OK;
        }

        if( !isset($value['size'] ) )
        {
            $value['size'] = filesize($value['tmp_name'] );
        }

        if( !isset($value['type'] ) )
        {
            $value['type'] = 'application/octet-stream';
        }

        // @link http://php.net/manual/en/errorfunc.constants.php
        switch( $value['error'] )
        {
          case UPLOAD_ERR_CANT_WRITE:
            throw new ErrorBaseValidator( $this, self::$cantWriteKey );

          case UPLOAD_ERR_EXTENSION:
            throw new ErrorBaseValidator( $this, self::$extensionKey );

          case UPLOAD_ERR_FORM_SIZE:
                throw new ErrorBaseValidator( $this, self::$maxSizeKey, array( self::$maxSizeKey => 0, 'size' => (int) $value['size'] ) );

          case UPLOAD_ERR_INI_SIZE:
                $max = ini_get('upload_max_filesize');
                if( $this->getOption( self::$maxSizeKey ) )
                {
                    $max = min( $max, $this->getOption( self::$maxSizeKey ) );
                }
                throw new ErrorBaseValidator( $this, self::$maxSizeKey, array( self::$maxSizeKey => $max, 'size' => (int) $value['size'] ) );

          case UPLOAD_ERR_NO_TMP_DIR:
            throw new ErrorBaseValidator( $this, self::$noTmpDirKey );

          case UPLOAD_ERR_PARTIAL:
            throw new ErrorBaseValidator( $this, self::$partialKey );

          case UPLOAD_ERR_OK:
              break;

          default:
            throw new InvalidArgumentException( sprintf( 'The file upload failed with an unknown error value.' ) );
        }

        // check file size
        if( $this->hasOption( self::$maxSizeKey ) && $this->getOption( self::$maxSizeKey ) < (int) $value['size'] )
        {
            throw new ErrorBaseValidator( $this, self::$maxSizeKey, array(self::$maxSizeKey => $this->getOption(self::$maxSizeKey), 'size' => (int) $value['size'] ) );
        }

        $mimeType = $this->getMimeType( (string) $value['tmp_name'], (string) $value['type'] );

        // check mime type
        if( $this->hasOption( self::$mimeTypeKey ) )
        {
            $mimeTypes = is_array( $this->getOption( self::$mimeTypeKey ) ) ? $this->getOption( self::$mimeTypeKey ) : $this->getMimeTypesFromCategory( $this->getOption( self::$mimeTypeKey ) );
            if( !in_array( $mimeType, array_map( 'strtolower', $mimeTypes ) ) )
            {
                throw new ErrorBaseValidator( $this, self::$mimeTypeKey, array( self::$mimeTypeKey => $mimeTypes, self::$mimeTypeKey => $mimeType ) );
            }
        }

        $class = $this->getOption( self::$validatedFileClassKey );

        return new $class($value['name'], $mimeType, $value['tmp_name'], $value['size'], $this->getOption('path'));
        }

        /**
        * Returns the mime type of a file.
        *
        * This methods call each mime_type_guessers option callables to
        * guess the mime type.
        *
        * This method always returns a lower-cased string as mime types are case-insensitive
        * as per the RFC 2616 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7).
        *
        * @param  string $file      The absolute path of a file
        * @param  string $fallback  The default mime type to return if not guessable
        *
        * @return string The mime type of the file (fallback is returned if not guessable)
        */
        protected function getMimeType( $file, $fallback )
        {
            foreach( $this->getOption( self::$mimeTypeGuessersKey ) as $method )
            {
                $type = call_user_func( $method, $file );

                if( $type !== null && $type !== false)
                {
                    return strtolower( $type );
                }
            }

            return strtolower( $fallback );
        }

        /**
        * Guess the file mime type with PECL Fileinfo extension
        *
        * @param  string $file  The absolute path of a file
        *
        * @return string The mime type of the file (null if not guessable)
        */
        protected function guessFromFileinfo( $file )
        {
            if( !function_exists( 'finfo_open' ) || !is_readable( $file ) )
            {
                return null;
            }

            if( !$finfo = new finfo( FILEINFO_MIME ) )
            {
                return null;
            }

            $type = $finfo->file( $file );

            // remove charset (added as of PHP 5.3)
            $pos = strpos($type, ';');
            if( $pos  !== false )
            {
                $type = substr( $type, 0, $pos );
            }
            return $type;
        }

        /**
         * Guess the file mime type with mime_content_type function (deprecated)
         *
         * @param  string $file  The absolute path of a file
         *
         * @return string The mime type of the file (null if not guessable)
         */
        protected function guessFromMimeContentType( $file )
        {
            if( !function_exists( 'mime_content_type' ) || !is_readable( $file ) )
            {
                return null;
            }

            return mime_content_type( $file );
        }

        /**
         * Guess the file mime type with the file binary (only available on *nix)
         *
         * @param  string $file  The absolute path of a file
         *
         * @return string The mime type of the file (null if not guessable)
         */
        protected function guessFromFileBinary($file)
        {
            ob_start();

            //need to use --mime instead of -i.
            passthru( sprintf( 'file -b --mime %s 2>/dev/null', escapeshellarg( $file ) ), $return );
            if ($return > 0)
            {
                ob_end_clean();

                return null;
            }
            $type = trim(ob_get_clean());

            if( !preg_match( '#^([a-z0-9\-]+/[a-z0-9\-]+)#i', $type, $match ) )
            {
                // it's not a type, but an error message
                return null;
            }

            return $match[1];
        }

        /**
         * Guess the file mime with tha Category array.
         *
         * @param  string $category
         *
         * @throws InvalidArgumentException
         * @return string The mime type
         */
        protected function getMimeTypesFromCategory($category)
        {
            $categories = $this->getOption( self::$mimeCategoriesKey );
            if( !isset( $categories[$category] ) )
            {
                throw new InvalidArgumentException( sprintf( 'Invalid mime type category "%s".', $category ) );
            }
            return $categories[$category];
        }

        /**
         * Returns true if the value is empty.
         *
         * @param  mixed $value  The input value
         * @return bool true if the value is empty, false otherwise
         * @see BaseValidator
         */
        protected function isEmpty( $value )
        {
            // empty if the value is not an array
            // or if the value comes from PHP with an error of UPLOAD_ERR_NO_FILE
            return ( !is_array( $value ) ) || ( is_array( $value ) && isset( $value['error'] ) && UPLOAD_ERR_NO_FILE === $value['error'] );
        }
    }
?>